//index.js
//获取应用实例
const app = getApp()
const defaultAvatarUrl = '../../images/avatardefault.png'
const request = require('../../utils/promise.js');
const common = require('../../utils/common.js');
Page({
  data: {
    StatusBar: app.globalData.StatusBar,
    CustomBar: app.globalData.CustomBar,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    TabCur: 0,
    avatarUrl: defaultAvatarUrl,
    avatarUrlUp: '',
    userInfo: [],
    WebUrl: app.globalData.weburl,
    arraylist: [],
    recordlist: [],
  },
  onLoad: function () {
    var openid = wx.getStorageSync('openid');
    console.log("openid", openid);
    var self = this;  // 保存 this 的引用  
    if (openid == "") {
      console.log("openidempty");
      self.wxlogin();
    }
    else {
      self.getUserInfo(openid);
    }
    this.loadOrder();
    this.loadHistory();
  },
  getUserInfo: function (openid) {
    console.log("getUserInfogogogo");
    var parm = {
      "openid": openid,
    };

    request.GET("/mdz/reguser/getuserinfo", parm).then(res => {
      console.log(res);
      if (res.data.code == "200") {
        this.setData({
          userInfo: res.data.data,
          avatarUrl: res.data.data.avatar
        });
      }
      else {
        common.CheckErrorForBusiness(res.data.msg);
      }
    })
  },
  tabSelect(e) {
    this.setData({
      TabCur: e.currentTarget.dataset.id,
    })
  },
  wxlogin: function () {
    var self = this;  // 保存 this 的引用  
    wx.login({
      success(res) {
        if (res.code) {
          wx.request({
            url: app.globalData.apiurl + '/mdz/reguser/login',
            data: {
              code: res.code
            },
            success(res) {
              console.log('登录成功', res.data);
              // 处理登录成功的逻辑，如保存token  
              wx.setStorageSync('openid', res.data.data.openid);
              wx.setStorageSync('sessionKey', res.data.data.sessionKey);

              self.getUserInfo(res.data.data.openid);
            }
          })
        } else {
          console.log('登录失败！' + res.msg)
        }
      }
    })
  },
  onChooseAvatar(e) {
    var that = this;
    const { avatarUrl } = e.detail
    that.setData({
      avatarUrl: e.detail.avatarUrl,
    })
    console.log('uploadImgURL', app.globalData.apiurl + '/mdz/reguser/uploadFile');
    wx.uploadFile({
      url: app.globalData.apiurl + '/mdz/reguser/uploadFile',
      filePath: e.detail.avatarUrl,
      name: 'file',
      formData: {
        'openid': wx.getStorageSync('openid')
      },
      success(res) {
        console.log('uploadImg', res);
        const data = JSON.parse(res.data)
        that.setData({
          avatarUrlUp: data.msg,
        })
        var openid = wx.getStorageSync('openid');
        that.getUserInfo(openid);
      }
    })
  },
  loadHistory: function () {
    // 尝试从本地存储获取历史记录数组，如果不是数组则默认为空数组  
    let historyArr = wx.getStorageSync('history');
    console.log('historyArr', historyArr);
    if (!Array.isArray(historyArr)) {
      historyArr = [];
    }
    var ids = ''
    historyArr.forEach(historyItem => {
      const val = historyItem;
      ids += val + ','
    });
    ids = ids.substring(0, ids.length - 1);
    console.log('ids', ids);
    var parm = {
      "contentIds": ids,
    };
    request.GET("/mdz/content/contentrecord", parm).then(res => {
      // console.log(res);
      if (res.data.code == "200") {
        this.setData({
          recordlist: res.data.rows
        });
      }
      else {
        common.CheckErrorForBusiness(res.data.msg);
      }
    })
  },
  loadOrder: function () {
    var parm = {
      "userId": 3,
    };
    request.GET("/mdz/content/videoorder", parm).then(res => {
      // console.log(res);
      if (res.data.code == "200") {
        this.setData({
          arraylist: res.data.rows
        });
      }
      else {
        common.CheckErrorForBusiness(res.data.message);
      }
    })
  },
  gotoLessionDetail: function (event) {
    console.log('index1', event.currentTarget.dataset.index);
    console.log('index1type', event.currentTarget.dataset.type);
    var url = common.getLessionDetailUrl(event.currentTarget.dataset.index,event.currentTarget.dataset.type);
    console.log('url',url);
    wx.navigateTo({
      url: url,
    })
  },
})
